//
// Created by oren on 2/9/23.
//
#include "TimeUtil.h"

namespace TimeUtil {

int fps_calc_inc(FpsCalc &impl) {
  uint64_t total_time = 0;
  uint64_t total_count = 0;
  uint64_t last_time = 0;
  uint64_t last_count = 0;

  {
    uint64_t now = now_us();
    if (!impl.total_count) {
      impl.total_start = now;
      impl.last_start = now;
    } else {
      uint64_t elapsed = now - impl.last_start;

      // print on each second
      if (elapsed >= 1000000) {
        total_time = now - impl.total_start;
        total_count = impl.total_count;
        last_time = now - impl.last_start;
        last_count = impl.total_count - impl.last_count;

        impl.last_start = now;
        impl.last_count = impl.total_count;
      }
    }

    impl.total_count++;
  }

  if (total_time) {
    impl.avg_fps = (float)total_count * 1000000 / (float)total_time;
    impl.ins_fps = (float)last_count * 1000000 / (float)last_time;
    return 1;
  } else {
    return 0;
  }
}
} // namespace TimeUtil